var http = require('http');
var url = require('url');
 
var chatroom = new Chatroom("EchoNet");
console.log("Created new chatroom");

http.createServer(function (req, res) {

//to post a message, the url must remsemble /post/helloworld                
var message = req.url.split("post/")[1];

if (message != undefined) {

                //if we dont have a cookie, set one.
       if (req.headers.cookie == undefined) {
                res.writeHead(200, {'Content-Type': 'text/plain',
                                       'Set-Cookie':  'thecookie:' + Date.now()
                });
                
        } 

                cookie = req.headers.cookie;
                
             //if the cookie exists, the user is returned, if the cookie does not exist, a user is created.
                user = chatroom.registerOrFindUser(cookie);
                chatroom.messages.push(user.userId + ":" + message);
                
        } else {
                res.write("Invalid url : format /post/mymessage")
        }
        
        res.write(chatroom.displayAllMessages());
  
        res.end("end of messages");
}).listen(1337, "127.0.0.1");


console.log('Server running at http://127.0.0.1:1337/');





/*User Object*/
function User(cookie) { 
  this.isObject = true;
  this.cookie   = cookie;
  this.userId   = "?";
}



/*Chatroom Class*/

function Chatroom(name) { 
  this.isObject = true;
  this.name    = name;
  this.users    = [];
  this.messages = [];
}


/*displayAllMessages*/
Chatroom.prototype.displayAllMessages = function() {
        var messageText = "";
        
        for (i= this.messages.length; i--; i >0) {
                        messageText += this.messages[i] + "\n";
        }
        
        return messageText;
}


/*registerOrFindUser*/
Chatroom.prototype.registerOrFindUser = function(cookie) {

var theUser = undefined;          

        // try to see if we already have this user in this chatroom, if we do, return them
        for (i in this.users) {
                if (this.users[i].cookie == cookie) {
                        theUser = this.users[i];
                        theUser.userId = i;
                        break;
                }
        }
        
        if(theUser == undefined) {
                console.log("user doesnt already exist, therefore creating it now");
                // if chatroom doesnt already contain the user with the cookie passed in,
                // create a new user and add to chatroom's list of users
                theUser = new User(cookie);
                
                this.users.push(theUser);
        }
         
        return theUser;
        
}